#!/usr/local/bin/python
#-*- coding:utf-8 -*-

__author__ = 'dong'

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import httplib
import urllib
#服务地址
host = "yunpian.com"
#端口号
port = 80
#版本号
version = "v1"

#智能匹配模版短信接口的URI
sms_send_uri = "/" + version + "/sms/send.json"

def send_sms(apikey, text, mobile):
    """
    通用接口发短信
    """
    params = urllib.urlencode({'apikey': apikey, 'text': text, 'mobile':mobile})
    headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
    conn = httplib.HTTPConnection(host, port=port, timeout=30)
    conn.request("POST", sms_send_uri, params, headers)
    response = conn.getresponse()
    response_str = response.read()
    conn.close()
    return response_str

def explainPhoneNumber(number, templates):
    a = []
    apikey = "xxxxxxxxxxxxxxxxxxxx"
    text = str(templates)

    number = str(number).replace(' ', '')
    number = str(number).replace('，', ',')
    number = str(number).replace('\r\n', ',')
    number = str(number).replace('\n', ',')
    number = str(number).replace('\r', ',')
    for mobile in number.split(','):
        try:
            if len(mobile) == 11:
                result = '信息发送中 '+ mobile + " " + send_sms(apikey, text, mobile)
            else:
                result = mobile + ' 发送出错'
        except IOError:
            print IOError.strerror
        a.append(str(result) + '\r\n')
    r = ''.join(a)
    return r
